package com.lik.javadeep.basic.sort;

public class SelectionSort {
    public static void main(String[] args) {
        int[] ints = {9, 3, 5, 2, 9, 6, 18};
        selectAndSort(ints);

        for (int i : ints) {
            System.out.println(i);
        }

    }

    private static void selectAndSort(int[] ints) {
        int maxIndex;
        for (int i = 0; i <= ints.length - 1; i++) {
            maxIndex = selectMax(ints.length - i, ints.length - i - 1, ints);
            swap(ints, maxIndex, ints.length - 1 - i);
        }
    }

    /**
     * 在startPosition前的n个元素中，寻找最大值
     *
     * @param n
     * @param startPosition
     * @param ints
     * @return
     */
    private static int selectMax(int n, int startPosition, int[] ints) {
        int maxIndex = startPosition;
        for (int i = 1; i < n; i++) {
            if (ints[startPosition - i] > ints[maxIndex]) {
                maxIndex = startPosition - i;
            }
        }
        return maxIndex;
    }

    private static void swap(int[] array, int aIndex, int bIndex) {
        int temp = array[aIndex];
        array[aIndex] = array[bIndex];
        array[bIndex] = temp;
    }
}
